<script setup lang="ts">
import type {TableProps} from 'ant-design-vue';

import type {UnwrapRef} from 'vue';

import {computed, onMounted, reactive, ref} from 'vue';

import {message} from 'ant-design-vue';

import {editApi, page, exportApi} from '#/api';


const globalIndexOffset = computed(
    () => (paginationParams.current - 1) * paginationParams.size,
);
const editableData: UnwrapRef<Record<string, any>> = reactive({});
const dataSource = ref([]);
const columns = ref([
  {
    title: '序号',
    key: 'index',
    customRender: ({index}) => {
      return globalIndexOffset.value + index + 1; // 0 → 1, 1 → 2...
    },
    width: 20,
  },
  {
    title: '资产编码',
    dataIndex: 'assetCode',
    key: 'assetCode',
    width: 100,
    align: 'center',
  },
  {
    title: '资产名称',
    dataIndex: 'assetName',
    key: 'assetName',
    width: 140,
    align: 'center',
  },
  {
    title: '楼层',
    dataIndex: 'floor',
    key: 'floor',
    width: 60,
    align: 'center',
  },
  {
    title: '位置号',
    dataIndex: 'address',
    key: 'address',
    width: 60,
    align: 'center',
  },
  {
    title: '颜色',
    dataIndex: 'color',
    key: 'color',
    width: 60,
    align: 'center',
  },
  {
    title: '备注',
    dataIndex: 'remark',
    key: 'remark',
    width: 100,
    align: 'center',
  },
  {
    title: '标签状态',
    dataIndex: 'abnormalReason',
    key: 'abnormalReason',
    width: 80,
    align: 'center',
  },
  {
    title: '盘点状态',
    dataIndex: 'inventoryStatus',
    key: 'inventoryStatus',
    width: 80,
    align: 'center',
  },
  {
    title: '盘点人',
    dataIndex: 'inventoryBy',
    key: 'inventoryBy',
    width: 80,
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    key: 'operation',
    width: 80,
    align: 'center',
    fixed: 'right',
  },
]);

// {
//   "query": {
//   "projectName": "丽泽",
//     "assetCode": "",
//     "assetName": "椅子-员工椅",
//     "floor": "2F",
//     "address": "",
//     "inventoryStatus": "全部",
//     "reason": "全部"
// },
//   "current": 1,
//   "size": 15
// }
const total = ref(0);

const pagination = computed(() => ({
  total: total.value,
  current: paginationParams.current,
  pageSize: paginationParams.size,
  showTotal: (total, range) => `${range[0]}-${range[1]} 条，共 ${total} 条`,
  // showTotal:"total => `Total ${total} items`"
}));
const paginationParams = reactive({
  current: 1,
  size: 10,
  query: {
    projectName: '',
    assetCode: '',
    assetName: '',
    floor: '',
    address: '',
    inventoryStatus: '',
    reason: '',
  },
});

onMounted(() => {
  fetchData();
});

const fetchData = async () => {
  const res = await page(paginationParams);
  console.log(res);
  dataSource.value = res.records;
  total.value = res.total;
};

const reload = () => {
  paginationParams.current = 1;
  fetchData();
};

const edit = (id: string) => {
  editableData[id] = cloneDeep(dataSource.value.find((item) => id === item.id));
};
const save = async (id: string) => {
  Object.assign(
      dataSource.value.find((item) => id === item.id),
      editableData[id],
  );
  await editApi(editableData[id]);
  message.success('保存成功');
  delete editableData[id];
};
const cancel = (id: string) => {
  delete editableData[id];
};
const cloneDeep = (origin: any) => {
  return JSON.parse(JSON.stringify(origin));
};
const handleTableChange: TableProps['onChange'] = (
    pag: { current: number; pageSize: number },
    filters: any,
    sorter: any,
) => {
  paginationParams.current = pag.current;
  paginationParams.size = pag.pageSize;

  fetchData();
};


const mExport = () => {
  if(!paginationParams.query.projectName){
    message.error("请先输入项目名称")
    return;
  }
  exportApi(paginationParams.query.projectName).then((res)=>{
    console.log('download',res)
// 创建一个指向Blob的URL[citation:1][citation:2]
    const blobUrl = window.URL.createObjectURL(new Blob([res]));

    // 创建一个隐藏的<a>标签并触发点击[citation:1][citation:2]
    const link = document.createElement('a');
    link.href = blobUrl;
    link.download = paginationParams.query.projectName+".xls"; // 设置下载的文件名[citation:1][citation:2]
    link.style.display = 'none';

    document.body.appendChild(link);
    link.click(); // 模拟点击下载[citation:1][citation:2]

    // 清理和释放URL对象[citation:1][citation:2]
    document.body.removeChild(link);
    window.URL.revokeObjectURL(blobUrl);
  })
}
const fileList = ref([]);
const handleChange = (info: UploadChangeParam) => {
  if (info.file.status !== 'uploading') {
    console.log(info.file, info.fileList);
  }
  if (info.file.status === 'done') {
    message.success(`${info.file.name} 数据导入成功，页面已重新加载`);
    setTimeout(()=>{
      reload();
    },100)
  } else if (info.file.status === 'error') {
    message.error(`${info.file.name} 数据导入失败`);
    setTimeout(()=>{
      reload();
    },100)
  }
}
</script>
<template>
  <div class="wrap-page">
    <div class="wrap-action">
      <a-space>
        项目名称
        <a-input
            v-model:value="paginationParams.query.projectName"
            style="width: 100px"
        />
        资产类型
        <a-input
            v-model:value="paginationParams.query.assetName"
            style="width: 80px"
        />
        楼层
        <a-input
            v-model:value="paginationParams.query.floor"
            style="width: 80px"
        />
        位置
        <a-input
            v-model:value="paginationParams.query.address"
            style="width: 80px"
        />
        资产码
        <a-input
            v-model:value="paginationParams.query.assetCode"
            style="width: 80px"
        />
        盘点状态
        <a-select
            v-model:value="paginationParams.query.inventoryStatus"
            style="width: 100px"
        >
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="已盘">已盘</a-select-option>
          <a-select-option value="未盘">未盘</a-select-option>
          <a-select-option value="新增">新增</a-select-option>
        </a-select>
        资产状态
        <a-select
            v-model:value="paginationParams.query.reason"
            style="width: 100px"
        >
          <a-select-option value="">全部</a-select-option>
          <a-select-option value="无异常">无异常</a-select-option>
          <a-select-option value="标签卷边">标签卷边</a-select-option>
          <a-select-option value="无标签">无标签</a-select-option>
        </a-select>
        <a-button type="primary" @click="reload">查找</a-button>
        <a-upload
            v-model:file-list="fileList"
            name="file"
            action="/api/project/importForce"
            :data="{ projectName:paginationParams.query.projectName }"
            @change="handleChange"
            :showUploadList="false"
        >
          <a-button type="primary" pl>
            导入
          </a-button>
        </a-upload>
        <a-button type="primary" @click="mExport">导出</a-button>
      </a-space>
    </div>
    <div class="wrap-content">
      <a-table
          :data-source="dataSource"
          :columns="columns"
          :pagination="pagination"
          @change="handleTableChange"
          show-total="Total items"
      >
        <template #bodyCell="{ column, text, record }">
          <template
              v-if="
              [
                'assetName',
                'floor',
                'address',
                'color',
                'remark',
                'abnormalReason',
              ].includes(column.dataIndex)
            "
          >
            <div>
              <a-input
                  v-if="editableData[record.id]"
                  v-model:value="editableData[record.id][column.dataIndex]"
                  style="margin: -5px 0"
              />
              <template
                  v-else-if="['abnormalReason'].includes(column.dataIndex)"
              >
                <a-tag
                    v-if="text === '标签卷边' || text === '无标签'"
                    color="red"
                >
                  {{ text }}
                </a-tag>
                <a-tag v-else color="blue">无异常</a-tag>
              </template>
              <template v-else>
                {{ text }}
              </template>
            </div>
          </template>
          <template v-else-if="column.dataIndex === 'inventoryStatus'">
            <a-tag v-if="text === '已盘'" color="blue">{{ text }}</a-tag>
            <a-tag v-else-if="text === '未盘'" color="red">{{ text }}</a-tag>
            <a-tag v-else color="orange">{{ text }}</a-tag>
          </template>
          <template v-else-if="column.dataIndex === 'operation'">
            <div class="editable-row-operations">
              <span v-if="editableData[record.id]">
                <a-space>
                  <a-button type="primary" size="small" @click="save(record.id)"
                  >保存</a-button
                  >
                  <a-button
                      type="primary"
                      danger
                      size="small"
                      @click="cancel(record.id)"
                  >取消</a-button
                  >
                </a-space>
              </span>
              <span v-else>
                <a-button type="primary" size="small" @click="edit(record.id)"
                >修改</a-button
                >
              </span>
            </div>
          </template>
        </template>
      </a-table>
    </div>
  </div>
</template>
<style lang="less" scoped>
.wrap-page {
  //margin: 12px;
  //padding:12px;
  //background: #fff;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.wrap-action {
  margin: 12px;
  background: #fff;
  padding: 12px;
  border-radius: 4px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}

.wrap-content {
  margin: 0 12px 12px 12px;
  background: #fff;
  flex: 1;
}
</style>
